<template>
  <div class="code-block-wrapper">
    <div class="code-block-header">
      <span class="lang-label" v-if="lang">{{ lang }}</span>
      <button class="copy-btn" @click="copyCode">{{ copied ? '已复制' : '复制' }}</button>
    </div>
    <pre class="hljs" :class="[lang]">
      <code ref="codeEl" v-html="highlightedCode"></code>
    </pre>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import hljs from 'highlight.js'
  const props = defineProps({
    code: { type: String, required: true },
    lang: { type: String, default: '' },
  })
  const copied = ref(false)
  const codeEl = ref(null)
  const highlightedCode =
    props.lang && hljs.getLanguage(props.lang)
      ? hljs.highlight(props.code, { language: props.lang }).value
      : hljs.highlightAuto(props.code).value
  function copyCode() {
    if (codeEl.value) {
      navigator.clipboard.writeText(props.code)
      copied.value = true
      setTimeout(() => (copied.value = false), 1200)
    }
  }
</script>

<script lang="ts">
  export default {}
</script>

<style scoped>
  .code-block-wrapper {
    background: #23272f;
    border-radius: 10px;
    margin: 18px auto;
    max-width: 90%;
    min-width: 0;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
    border: 1px solid #22272e;
    position: relative;
    overflow: auto;
  }
  .code-block-header {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 6px 14px 0 14px;
  }
  .lang-label {
    color: #bbb;
    font-size: 13px;
    margin-right: auto;
    font-family: 'JetBrains Mono', monospace;
  }
  .copy-btn {
    background: rgba(40, 40, 40, 0.7);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: 2px 10px;
    font-size: 13px;
    cursor: pointer;
    opacity: 0.7;
    transition:
      opacity 0.2s,
      background 0.2s;
    z-index: 2;
  }
  .copy-btn:hover {
    opacity: 1;
    background: #409eff;
    color: #fff;
  }
  pre {
    background: transparent !important;
    color: #f8f8f2;
    font-size: 15px;
    line-height: 1.7;
    margin: 0;
    padding: 0 20px 18px 20px;
    border-radius: 0 0 10px 10px;
    overflow-x: auto;
  }
  code {
    background: none !important;
    color: #f8f8f2;
    font-family: 'JetBrains Mono', 'Fira Mono', 'Menlo', 'Consolas', 'Liberation Mono', monospace;
    font-size: 15px;
  }
</style>
